import config from './config'
var utilMd5 = require('md5.js');
const METHOD = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE'
}
class Request {
  _baseUrl = config.baseUrl
  request(url, method, data, header) {
    let self = this
    let newData = this.concatData(data)
    data.sign = this.getSign(data)
    return new Promise(function (resolve, reject) {
      // setTimeout(() => {
        wx.request({
          url: (self._baseUrl || '') + url,
          data: data,
          method: method || METHOD.GET,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'X-Requested-Page': 'json'
          },
          success: function (res) {
            resolve(res.data)
          },
          fail: function (res) {
            reject(res.data)
          }
        })
      // }, 500)
    })
  }
  // objKeySort(obj) { //排序的函数
  //     var newkey = Object.keys(obj).sort();　　 //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  //     var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
  //     for (var i = 0; i < newkey.length; i++) { //遍历newkey数组
  //         newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  //     }
  //     return newObj; //返回排好序的新对象
  // }
  createTimeStamp() {
    return parseInt(new Date().getTime() / 1000) + ''
  }
  createRandom() {
    let len = 10
    let chars = 'abcdefhijkmnprstwxyz'
    let maxPos = chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd;
  }
  getSign(data) {
    let Appcode = 'n8OhPxZOtf3dRl9vjIxXBQQ4'
    let str = data.time + data.random + Appcode
    // Object.keys(data).forEach((item, index) => {
    //     key = key + '&' + item + '=' + data[item]
    // })
    return utilMd5.hexMD5(str)
  }
  concatData(data) {
    data.time = this.createTimeStamp()
    data.random = this.createRandom()
    return data
  }
}

export default new Request